"use strict";

var C = require('../common'),
    WebModule = require('../webmodule');

module.exports = {

    type: 'module',

    load: function (owner, modules, cb) {

        var rootModule = null, webModules = [];

        C._.each(modules, function (modCfg, moduleName) {
            modCfg || C.throwRequired('[' + owner.stack + '].modules.[' + moduleName + ']');
            modCfg.route || C.throwRequired('[' + owner.stack + '].modules.[' + moduleName + '].route');

            if (modCfg.route === '' || modCfg.route === '/') {
                if (rootModule) {
                    throw new C.Error.ConfigError('[' + owner.stack + '].modules.[' + moduleName + '].route', 'Duplicate root route.');
                }
                rootModule = moduleName;
                return;
            }

            webModules.push(new WebModule(owner, moduleName, modCfg));
        });

        if (rootModule) {
            webModules.push(new WebModule(owner, rootModule, modules[rootModule]));
        }

        owner.modules = {};

        return C.async.eachSeries(webModules, function (webModule, cb2) {
            var name = webModule.name;
            console.log('Loading module [' + name + '] ...');

            webModule.bootstrap(null, function(err) {
                if (err) return cb2(err);

                owner.modules[name] = webModule;
                owner.console('Module [' + name + '@' + webModule.version + '] is successfully loaded.');
                console.log();
                cb2();
            });
        }, cb);
    }
};